package dyyx.db;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Component;

import dyyx.util.CommUtil;


@Component
public class DBInitBean {
	
	//  @Autowired 注意使用 @Qualifier注解 指定 bean name  ,否则 默认按byType自动注入 注入第一个匹配的
	
	// @Autowired
	// @Qualifier("db1SqlSessionFactory")
	// private SqlSessionFactory db1SqlSessionFactory;
	// @Autowired
	// @Qualifier("db2SqlSessionFactory")
	// private SqlSessionFactory db2SqlSessionFactory;
	
	// @Resource 默认按 name 注入
	@Resource
	private SqlSessionFactory db1SqlSessionFactory;
	@Resource
	private SqlSessionFactory db2SqlSessionFactory;

	
	
	
	@PostConstruct
	public void init()throws Exception{
		
		System.out.println("db1SqlSessionFactory="+db1SqlSessionFactory);
		System.out.println("db2SqlSessionFactory="+db2SqlSessionFactory);

		
		runSql(db1SqlSessionFactory,"sql/db1/init.sql");
		runSql(db2SqlSessionFactory,"sql/db2/init.sql");

	}
	
	
	private void runSql(SqlSessionFactory sqlSessionFactory,String file)throws Exception{
		
		// System.out.println();
		// System.out.println("file="+file);
		
		String str = "sqlSessionFactory="+sqlSessionFactory +",file="+file;
		System.out.println("runSql start,"+str);

		
		String sqlstr = CommUtil.readFromResource(file, null);
		System.out.println(sqlstr);
		String[]sqls = StringUtils.split(sqlstr, ";");
		SqlSession session = sqlSessionFactory.openSession(true);
		
		for(String sql:sqls){
			if(StringUtils.isBlank(sql)){
				continue;
			}
			session.getConnection().createStatement().executeUpdate(sql);
		}
		session.close();
		
		System.out.println("runSql done,"+str+" \n\n\n");

		
	}
	

	

	
}
